package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class EasyExcelListener extends AnalysisEventListener<SubjectData> {


    // 因为EasyExcelListener不能交给Spring管理 需要自己创建 所以无法注入service
    // 所以需要构建有参构造 在new对象的时候将service注入
    public EduSubjectService eduSubjectService;
    public EasyExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    /**
     * 一行一行的读取内容
     * @param subjectData
     * @param analysisContext
     */
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new GuliException(20001,"文件数据为空");
        }
        //一行一边读取 每次读取有两个值（excel需要读取的列） 一级分类和二级分类
        EduSubject oneEduSubject = this.existOneSubject(eduSubjectService,subjectData.getOneSubjectName());
        if (oneEduSubject == null){
            oneEduSubject = new EduSubject();
            oneEduSubject.setParentId("0");
            oneEduSubject.setTitle(subjectData.getOneSubjectName());//一级分类名称
            eduSubjectService.save(oneEduSubject);
        }
        //判断二级分类
        String pid = oneEduSubject.getId();
        EduSubject twoEduSubject = this.existTwoSubject(eduSubjectService,subjectData.getOneSubjectName(),pid);
        if (twoEduSubject == null){
            twoEduSubject = new EduSubject();
            twoEduSubject.setParentId(pid);
            twoEduSubject.setTitle(subjectData.getTwoSubjectName());//一级分类名称
            eduSubjectService.save(twoEduSubject);
        }
    }

    /**
     * 读取完成后的操作
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    /**
     * 判断一级分类不能重复添加
     * @param eduSubjectService
     * @param name
     * @return
     */
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id","0");
        EduSubject eduSubject = eduSubjectService.getOne(queryWrapper);
        return eduSubject;
    }

    /**
     * 判断二级分类不能重复添加
     * @param eduSubjectService
     * @param name
     * @return
     */
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        EduSubject eduSubject = eduSubjectService.getOne(queryWrapper);
        return eduSubject;
    }
}
